<?php

namespace app\admin\controller\xykeep\goods;

use addons\epay\library\Service;
use app\api\model\xykeep\goods\Order as apiGoodsOrder;
use app\api\model\xykeep\User;
use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\admin\model\xykeep\delivery\Company as DeliveryCompany;
use app\admin\model\xykeep\Config as ConfigModel;
use fast\Http;
use think\response\Json;

/**
 * VIP订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\xykeep\goods\Order
     */
    protected $model = null;
    protected $relationSearch = true;
    protected $searchFields = 'order_sn,user.nickname';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\xykeep\goods\Order;
        $this->view->assign("payTypeList", $this->model->getPayTypeList());
        $this->view->assign("platformList", $this->model->getPlatformList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->assignconfig('statusList',$this->model->getStatusList());
    }


    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->with(['item','user'])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }


    /**
     * 详情
     *
     * @param $id
     */
    public function detail($id = null)
    {
        $row = $this->model->with(['item','user'])->where(['order.id'=>$id])->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    /**
     * 退款
     */
    public function refund($id = null)
    {
        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if($row['status'] < 1){
            $this->error(__('订单状态错误', ''));
        }

            $result = false;
            Db::startTrans();
            try {
                //是否采用模型验证
                if ($this->modelValidate) {
                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                    $row->validateFailException()->validate($validate);
                }

                $result = $row->allowField(true)->save(['status'=>-3,'refundtime'=>time()]);

                $params = ['order'=>$row,'type'=>'goods'];
                \think\Hook::listen('xykeep_order_refund_after', $params);

                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if (false === $result) {
                $this->error(__('No rows were updated'));
            }
            $this->success('退款成功');
    }

    /**
     * 确认收货
     */
    public function take_delivery($id = null){
        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if($row['status'] != 2){
            $this->error(__('订单状态错误', ''));
        }

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }

            $result = $row->allowField(true)->save(['status'=>5,'take_delivery_time'=>time()]);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }



    /**
     * 物流查询
     */
    public function logistics($id = null)
    {
        $row = $this->model->with(['item','user'])->where(['order.id'=>$id])->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if($row['status'] < 2){
            $this->error(__('订单状态错误', ''));
        }

        // 查询接口
        $qurl = "https://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx";

        $config = ConfigModel::getValueByName('shop');


        if($config['kdnid'] == '' || $config['kdnkey']==''){
            $this->error(__('请到配置中心，商城配置中配置快递鸟参数', ''));
        }

        // 组装应用级参数
	    $requestData= "{".
        "'CustomerName': '',".
        "'OrderCode': '',".
        "'ShipperCode': '".$row['delivery_company_code']."',".
        "'LogisticCode': '".$row['delivery_no']."',".
        "}";
        // 组装系统级参数
        $datas = array(
            'EBusinessID' => $config['kdnid'],
            'RequestType' => '8001',
            'RequestData' => urlencode($requestData) ,
            'DataType' => '2',
        );
      
        $datas['DataSign'] = urlencode(base64_encode(md5($requestData.$config['kdnkey']))); //encrypt($requestData, $apiKey);
        //以form表单形式提交post请求，post请求体中包含了应用级参数和系统级参数

        $result = Http::sendRequest($qurl, $datas, 'POST', []);

        
        if ($result['ret'] == 1) {
            $exResult = json_decode($result['msg'], true);

            if (!$exResult['Success']) {
                $this->error($exResult['Reason'], '');
            }

            $this->success('','',$exResult);

        } else {
            $this->error($result['msg'], '');
        }
        
    }

    /**
     * 发货
     *
     * @param $id
     */
    public function delivery($id = null)
    {
        $row = $this->model->with(['item','user'])->where(['order.id'=>$id])->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if($row['status'] != 1){
            $this->error(__('订单状态错误', ''));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }

            $deliveryCompany = DeliveryCompany::get($params['delivery_company_id']);
            $result = $row->allowField(true)->save(['status'=>2,'delivery_no'=>$params['delivery_no'],'delivery_company'=>$deliveryCompany['name'],'delivery_company_code'=>$deliveryCompany['code'],'delivery_time'=>time()]);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 线下支付确认收款
     */
    public function offline_pay(){
        $params = $this->request->post();
        Db::startTrans();
        try {
            $order = $this->model->where(['order_sn'=>$params['order_sn']])->lock(true)->find();
            if($order['status']!==0){
                throw new \Exception('订单状态已更变');
            }

            $notify = [
                'order_sn' => $order['order_sn'],
                'transaction_id' => '',
                'notify_time' => date('Y-m-d H:i:s'),
                'pay_fee' => $order['total_fee'],
                'pay_type' => 'offline'
            ];
            $notify['payment_json'] = json_encode($notify);

            $apiCourseOrder = new apiGoodsOrder();
            $apiCourseOrder->paySuccess($order,$notify);
            Db::commit();
        } catch (ValidateException|PDOException|\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('确认收款成功');

    }
}
